package com.letv.android.client.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.android.client.constant.FragmentConstant;
import com.letv.android.client.controller.BasePlayController;
import com.letv.android.client.fragment.BasePlayFragment;
import com.letv.android.client.listener.OrientationSensorListener;
import com.letv.android.client.listener.PlayActivityCallback;
import com.letv.android.client.utils.ChangeOrientationHandler;
import com.letv.android.client.view.LetvPlayGestureLayout;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.listener.OnRelevantStateChangeListener;
import com.letv.core.utils.ScreenInfoUtils;
import com.letv.core.utils.UIsUtils;


public class BasePlayActivity extends LetvBaseActivity implements PlayActivityCallback {
    // 播放显示区域
    public Rect mRect;
    // 播放器之上的容器
    protected FrameLayout mPlayUpperLayout;
    // 播放器之上的容器
    protected FrameLayout mPlayUpper;
    // 播放器之上的手势层
    protected LetvPlayGestureLayout mPlayGestrue;
    // 播放器之下的容器（半屏才显示）
    protected RelativeLayout mPlayLower;
    private ImageView mBtnGestureLock;
    // 播放器的Fragment
    protected BasePlayFragment mPlayFragment;

    // 播放Controller
    public BasePlayController mPlayController;
    // 电量等相关状态变化
    private OnRelevantStateChangeListener mOnRelevantStateChangeListener;
    // 转屏handler
    private static Handler mOrientationHandler;
    // 转屏Listener
    private OrientationSensorListener mOrientationSensorListener;
    private SensorManager mSensorManager;
    private Sensor mSensor;
    // 是否全屏
    private boolean mFull = false;
    // 判断是否已注册广播
    private boolean isRegisterReceiver;
    // 打开方式；用来区别播放不动的视频
    private int mLaunchMode;
    // 浮球
//    private FloatBallUI mFloatBallUI;
    /**
     * 直播还是点播
     * 点播：PLAY_TYPE_ALBUM
     * 直播：PLAY_TYPE_LIVE
     */
    private int mPlayType;
    // 播放来源
    private int mFromLaunch;

    // 电量值
    private int mBatteryStatus;
    private int mBatteryPower;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mPlayUpperLayout != null) {
                mPlayUpperLayout.getGlobalVisibleRect(mRect);
                callAdsPlayInterface(PlayConstant.ON_VIDEORE_SIZE, false);
            }
        }
    };

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.letv_activity_base_play);
        initDataFromIntent();
        // 清除统计信息
//        LiveStatisticsInfo.destroy();
        initViews();
    }

    private void initViews() {
        mPlayUpperLayout = (FrameLayout) findViewById(R.id.play_upper_layout);
        mPlayUpper = (FrameLayout) findViewById(R.id.play_upper);
        mPlayLower = (RelativeLayout) findViewById(R.id.play_lower);
        mPlayGestrue = (LetvPlayGestureLayout) findViewById(R.id.play_gestrue);
        mBtnGestureLock = (ImageView) findViewById(R.id.gesture_lock);

        // 自定义旋转
        mOrientationHandler = new ChangeOrientationHandler(this);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mRect = new Rect();
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mOrientationSensorListener = new OrientationSensorListener(mOrientationHandler, this);

        mPlayFragment.setIntent(getIntent());
        showFragmentIfNeeded(mPlayFragment, false);

        // 初始化Controller
        initController();

        // 做全、半屏相应View处理
        initWindowDirection();
        registerReceiver();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        getIntent().putExtra("isLiveFromPush", LetvSDK.getInstance().isPush());
        
        if (mPlayFragment != null) {
            mPlayFragment.pause();
            mPlayFragment.stopPlayback();
            mPlayFragment.setFirstStart(true);
        }

        initDataFromIntent();
        mPlayController.format();
        mPlayController = null;

        initController();
        initWindowDirection();

        // 重新刷新电量、时间、信号
        if (mOnRelevantStateChangeListener != null && ScreenInfoUtils.reflectScreenState(mContext)) {
            mOnRelevantStateChangeListener.onTimeChange();
            mOnRelevantStateChangeListener.onBatteryChange(mBatteryStatus, mBatteryPower);
            mOnRelevantStateChangeListener.onNetChange();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        
        //统计播放
        mPlayController.onResume();
        callAdsPlayInterface(PlayConstant.ON_ACTIVITY_RESUME, false);

        // 调整亮度
        float britness = PreferencesManager.getInstance(mContext).getBritness();
        if (britness != 0) {
            mPlayController.setBrightness(britness);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayFragment != null) {
            mPlayFragment.pause();
        }
        callAdsPlayInterface(PlayConstant.ON_ACTIVITY_PAUSE, false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mPlayFragment != null) {
            mPlayFragment.pause();
        }
        //统计播放
        mPlayController.onStop();
    }

    /**
     * 页面改变时，改变控件尺寸
     * */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }

        if (mPlayController.onKeyDown(keyCode, event)) {
            return true;
        }
        boolean ss = super.onKeyDown(keyCode, event);
        if (mPlayController != null) {
            int volNum = mPlayController.getCurSoundVolume();
            boolean isUp = false;
            if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                volNum += 1;
                isUp = true;
            } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                volNum -= 1;
                isUp = false;
            }
            mPlayController.curVolume(mPlayController.getMaxSoundVolume(), volNum, isUp);
        }
        return ss;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN && mPlayController != null) {
            // 开启长时间光看提醒
            mPlayController.startLongWatchCountDown();
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 读取加载模式
     * */
    private void initDataFromIntent() {
        Intent intent = getIntent();
        mPlayType = intent.getIntExtra(PlayConstant.PLAY_TYPE, PlayConstant.PLAY_TYPE_ALBUM);
        mLaunchMode = intent.getIntExtra("launchMode", 0);
        mFromLaunch = intent.getIntExtra("from", PlayConstant.LAUNCH_FROM_UNKONW);
        mFull = intent.getBooleanExtra(PlayConstant.LIVE_FULL_ONLY, false);
        if (mLaunchMode == 0) {
            String path = null;
            if (null != getIntent() && null != getIntent().getData()) {
                Uri uriPath = getIntent().getData();
                String scheme = uriPath.getScheme();
                if (scheme == null || scheme.equals("file")) {
                    path = uriPath.getPath();
                } else {
                    path = uriPath.toString();
                }
            }
            mLaunchMode = PlayConstant.LAUNCH_MODE_URI;
            intent.putExtra("launchMode", PlayConstant.LAUNCH_MODE_URI);
            intent.putExtra("uri", path);
            intent.putExtra("seek", 0);
            intent.putExtra("playMode", PlayConstant.PLAY_MODE_SYSTEM);
        }
        if (mFromLaunch == PlayConstant.LAUNCH_FROM_PUSH) { // 13
            LetvSDK.getInstance().setPush(true);
        } else if (intent.getBooleanExtra("isFromPush", false)) {
            LetvSDK.getInstance().setPush(true);
        } else if (intent.getBooleanExtra("isLiveFromPush", false)) {
            LetvSDK.getInstance().setPush(true);
        }
    }

    /**
     * 根据播放形势不一样，生成不同的PlayController
     * */
    private void initController() {
        mPlayController = BasePlayController.getPlayController(this, mLaunchMode, mFull, this);
        mPlayFragment.setStateChangeListener(mPlayController);
        mPlayFragment.setPlayFragmentListener(this);

        mOrientationSensorListener.setJustLandscape(mFull);
        mOnRelevantStateChangeListener = mPlayController;
    }

    /**
     * 初始化页面尺寸
     * */
    private void initWindowDirection() {
        boolean isLandscape = UIsUtils.isLandscape(this);
        mBtnGestureLock.setVisibility(isLandscape ? View.GONE : View.VISIBLE);
        if (isLandscape) {
            mBtnGestureLock.setVisibility(View.GONE);
            mPlayLower.setVisibility(View.GONE);
            mPlayLower.requestLayout();
            UIsUtils.zoomViewFull(mContext,mPlayUpperLayout);
            UIsUtils.fullScreen(this);
        } else {
            mBtnGestureLock.setVisibility(View.VISIBLE);
            mPlayLower.setVisibility(View.VISIBLE);
            mPlayLower.requestLayout();
            UIsUtils.zoomView(mContext,320, 180, mPlayUpperLayout);
            UIsUtils.cancelFullScreen(this);
            if (mLaunchMode == PlayConstant.LAUNCH_MODE_LIVE_LUNBO) {
                mOrientationSensorListener.setLock(false);
                mPlayController.wakeLock();
            }
        }

        mPlayController.changeDirection(isLandscape);
        mHandler.sendEmptyMessageDelayed(0, 1000);
        showThirdPartBtnState(isLandscape);
    }

    // 第三方进入时需要显示退出按钮
    private void showThirdPartBtnState(boolean isLandscape) {
        // TODO OPEN m站回跳
        // if (!isLandscape && BaseApplication.getInstance() != null) {
        // mThirdPartName = BaseApplication.getInstance().getThirdPartName();
        // if (!TextUtils.isEmpty(mThirdPartName)) {
        // mBackButton.setText(getResources().getString(R.string.back_to) + mThirdPartName);
        // mBackButtonLayout.setVisibility(View.VISIBLE);
        // mBackButton.setOnClickListener(new View.OnClickListener() {
        // @Override
        // public void onClick(View v) {
        // //退出整个应用
        // ActivityUtils.getInstance().removeAll();
        // }
        // });
        // } else {
        // mBackButtonLayout.setVisibility(View.GONE);
        // }
        // } else {
        // mBackButtonLayout.setVisibility(View.GONE);
        // }
    }

    /**
     * 注册关于监听 电量，时间，网络状态、屏幕状态的监听
     * */
    public void registerReceiver() {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            filter.addAction(Intent.ACTION_TIME_TICK);
            filter.addAction(Intent.ACTION_BATTERY_CHANGED);
            filter.addAction(Intent.ACTION_HEADSET_PLUG);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_USER_PRESENT);
            registerReceiver(mBroadcastReceiver, filter);
            mSensorManager.registerListener(mOrientationSensorListener, mSensor, SensorManager.SENSOR_DELAY_GAME);
            isRegisterReceiver = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消关于监听 电量，时间，网络状态的监听
     * */
    public void unregisterReceiver() {
        try {
            if (isRegisterReceiver) {
                unregisterReceiver(mBroadcastReceiver);
                mSensorManager.unregisterListener(mOrientationSensorListener);
                isRegisterReceiver = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听网络，电量，时间
     * */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {// 监听每分钟的时间变化
                if (mOnRelevantStateChangeListener != null) {
                    mOnRelevantStateChangeListener.onTimeChange();
                }
            } else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {// 监听网络连接状态变化
                if (mOnRelevantStateChangeListener != null && ScreenInfoUtils.reflectScreenState(mContext)) {
                    mOnRelevantStateChangeListener.onNetChange();
                }
            } else if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {// 监听电量变化
                mBatteryStatus = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);// 获得电池状态
                int level = intent.getExtras().getInt("level", 0);// 获得当前电量
                int scale = intent.getExtras().getInt("scale", 100);// 获得总电量
                mBatteryPower = level * 100 / scale;
                if (mOnRelevantStateChangeListener != null) {
                    mOnRelevantStateChangeListener.onBatteryChange(mBatteryStatus, mBatteryPower);
                }
            } else if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
                if (mOnRelevantStateChangeListener != null) {
                    mOnRelevantStateChangeListener.onHeadsetPlug();
                }
            } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                // 锁屏
                if (mPlayFragment != null) {
                    mPlayFragment.setScreenLock(true);
                    mPlayFragment.pause();
                }
                if (mPlayController != null) {
                    mPlayController.lockScreenPause();
                }
            } else if (Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {// 解锁
                if (mPlayFragment != null) {
                    mPlayFragment.setScreenLock(false);
                    mPlayFragment.resume();
                }
                if (mPlayController != null) {
                    mPlayController.unLockSceenResume();
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver();
        LetvSDK.getInstance().setPush(false);
        callAdsPlayInterface(PlayConstant.ON_ACTIVITY_EXIT, false);

        if (null != mPlayController) {
            mPlayController.onDestroy();
        }

        mPlayUpper.removeAllViews();
        mPlayLower.removeAllViews();
        mPlayUpperLayout.removeAllViews();
        mPlayController = null;

        mPlayUpper = null;
        mPlayLower = null;
        mPlayUpperLayout = null;
//        LiveStatisticsInfo.destroy();
    }

    /**
     * 广告接口回调播放各种状态
     *
     * @param whichStatus
     */
    private void callAdsPlayInterface(int whichStatus, boolean isHand) {
        // TODO 广告需要封装
        // try {
        // if (mPlayController != null && mPlayController.mIVideoStatusInformer != null) {
        // switch (whichStatus) {
        // case PlayConstant.ON_VIDEORE_SIZE:
        // mPlayController.mIVideoStatusInformer.OnVideoResize(rect);
        // break;
        // case PlayConstant.ON_ACTIVITY_PAUSE:
        // mPlayController.mIVideoStatusInformer.OnActivityPause();
        // break;
        // case PlayConstant.ON_ACTIVITY_RESUME:
        // mPlayController.mIVideoStatusInformer.OnActivityResume();
        // break;
        // case PlayConstant.ON_ACTIVITY_EXIT:
        // mPlayController.mIVideoStatusInformer.OnActivityExit();
        // break;
        // case PlayConstant.ON_VIDEO_START:
        // mPlayControllerPlayerLibs.mIVideoStatusInformer.OnVideoStart(isHand);// 正片开始播放
        // break;
        // case PlayConstant.ON_VIDEO_PAUSE:
        // mPlayControllerPlayerLibs.mIVideoStatusInformer.OnVideoPause(isHand);// 正片暂停
        // // 是否由用户主动触发
        // break;
        // case PlayConstant.ON_VIDEO_RESUME:
        // mPlayControllerPlayerLibs.mIVideoStatusInformer.OnVideoResume(isHand);// 正片继续
        // // 是否由用户主动触发
        // break;
        // case PlayConstant.ON_VIDEO_COMPLATE:
        // mPlayControllerPlayerLibs.mIVideoStatusInformer.OnVideoComplate();// 当视频播放完成
        // break;
        // case PlayConstant.ON_VIDEO_ERROR:
        // mPlayControllerPlayerLibs.mIVideoStatusInformer.onVideoError();// 当视频播放错误
        // break;
        // }
        // }
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
    }

    @Override
    public String[] getAllFragmentTags() {
        return FragmentConstant.ALBUM_FRAGMENT_TAG_ARRAY;
    }

    @Override
    public String getActivityName() {
        return BasePlayActivity.class.getName();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    /****************** PlayActivityCallback **********************/

    @Override
    public void callAdsInterface(int whichStatus, boolean isHand) {
        callAdsPlayInterface(whichStatus, isHand);
    }

    @Override
    public void cancelLongTimeWatch() {
        if (mPlayController != null) {
            mPlayController.cancelLongTimeWatch();
        }
    }

    @Override
    public int getPlayLevel() {
        if (mPlayController != null) {
            return mPlayController.getPlayLevel();
        }
        return LetvSDK.getInstance().getDefaultLevel();
    }

    @Override
    public void blockStart() {
//        if (mPlayController instanceof PlayLiveController) {
//            ((PlayLiveController) mPlayController).blockStart();
//        }
    }

    @Override
    public void blockEnd() {
//        if (mPlayController instanceof PlayLiveController) {
//            ((PlayLiveController) mPlayController).blockEnd();
//        }
    }

    @Override
    public void blockTwiceAlert() {
//        if (mPlayController instanceof PlayLiveController) {
//            ((PlayLiveController) mPlayController).blockTwiceAlert();
//        }
    }

    @Override
    public void setLock(boolean isLock) {
        mOrientationSensorListener.setLock(isLock);
    }

    @Override
    public boolean isPlaying() {
        if (mPlayFragment != null) {
            return mPlayFragment.isPlaying();
        }
        return false;
    }

    @Override
    public void setEnforcementPause(boolean isPause) {
        if (mPlayFragment != null) {
            mPlayFragment.setEnforcementPause(isPause);
        }
    }

    @Override
    public boolean isEnforcementPause() {
        if (mPlayFragment != null) {
            return mPlayFragment.isEnforcementPause();
        }
        return false;
    }

    @Override
    public void setEnforcementWait(boolean isWait) {
        if (mPlayFragment != null) {
            mPlayFragment.setEnforcementWait(isWait);
        }
    }

    @Override
    public boolean isEnforcementWait() {
        if (mPlayFragment != null) {
            return mPlayFragment.isEnforcementWait();
        }
        return false;
    }

    @Override
    public int getCurrentPlayPosition() {
        if (mPlayFragment != null) {
            return mPlayFragment.getCurrentPosition();
        }
        return 0;
    }

    @Override
    public void playPause() {
        if (mPlayFragment != null) {
            mPlayFragment.pause();
        }
    }

    @Override
    public void playNet(String uriString, boolean isLive, boolean isDolby, int msec) {
        if (mPlayFragment != null) {
            mPlayFragment.playNet(uriString, isDolby, msec);
        }
    }

    @Override
    public void start(String url, boolean isAdsFinished) {
//        if (mPlayType == PlayConstant.PLAY_TYPE_LIVE) { // 直播
//            ((PlayLiveFragment) mPlayFragment).start(url, isAdsFinished);
//        }
    }

    @Override
    public void lockOnce(int orientation) {
        if (mOrientationSensorListener != null) {
            mOrientationSensorListener.lockOnce(orientation);
        }
    }

    @Override
    public void stopPlayback() {
        if (mPlayFragment != null) {
            mPlayFragment.stopPlayback();
        }
    }

    @Override
    public void finishPlayer() {
        if (mPlayFragment != null) {
            mPlayFragment.destroyVedioView();
        }
    }
}
